package arrAndstr;

import java.util.Arrays;

/*
    289. 生命游戏
    优化思路：
        细胞前后一块统计有四种状态，
            死 -> 死
            死 -> 活
            活 -> 死
            活 -> 活
       那么我们可以记录这四种状态，即既能够知道之前状态还能知道现在状态，然后再判断即可
 */
public class T289 {

    public static void main(String[] args) {
        int[][] array = new int[][]{
                {1, 1},
                {1, 0}
        };
        gameOfLife(array);

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                System.out.print(array[i][j] + " ");
            }
        }
    }

    public static void gameOfLife(int[][] board) {
        int m = board.length;
        int n = board[0].length;
        int[][] oldArray = new int[m][n];
        for (int i = 0; i < m; i++) {
            System.arraycopy(board[i], 0, oldArray[i], 0, n);
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int rangeNum = getRangeNum(oldArray, i, j);
                if (board[i][j] == 1 && (rangeNum < 2 || rangeNum > 3)) {    //活细胞
                    board[i][j] = 0;
                }
                if (board[i][j] == 0 && rangeNum==3) {
                    board[i][j] = 1;
                }
            }
        }
    }

    private static int getRangeNum(int[][] array, int rowIndex, int columnIndex) {
        int row = array.length;
        int column = array[0].length;
        int result = 0;
        if (rowIndex!=0) {  // 上三个
            if (array[rowIndex-1][columnIndex]==1)  result++;
            if (columnIndex!=0 && array[rowIndex-1][columnIndex-1]==1)  result++;
            if (columnIndex!=column-1 && array[rowIndex-1][columnIndex+1]==1)   result++;
        }
        if (rowIndex!= row-1) { // 下三个
            if (array[rowIndex+1][columnIndex]==1)  result++;
            if (columnIndex!=0 && array[rowIndex+1][columnIndex-1]==1)  result++;
            if (columnIndex!=column-1 && array[rowIndex+1][columnIndex+1]==1)   result++;
        }
        if (columnIndex != 0 && array[rowIndex][columnIndex-1]==1) { // 左
            result++;
        }
        if (columnIndex != column-1 && array[rowIndex][columnIndex+1]==1) {  // 右
            result++;
        }

        return result;
    }
}
